<script setup lang="ts">
import { TransformControls, Cylinder } from '@tresjs/cientos'
import { Object3D, Vector3 } from 'three'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ThemeVO } from '@/api/pb/theme'
import { useLoaderStorage } from '@/store/modules/web3d/loader'

const loader = useLoaderStorage()

const message = useMessage()

const theme = inject<Ref<ThemeVO>>('theme')!
const isEdit = ref(false)
const defaultPosition = ref(new Vector3(0, 4, 0))
// 初始点位编辑对象
const spawnPoint = shallowRef<{
  instance: Object3D
}>()

watch(isEdit, (value) => {
  if (spawnPoint.value) {
    spawnPoint.value.instance.visible = value
  }
})

const edit = (editPosition: Ref<Vector3>) => {
  reset()
  isEdit.value = true

  editPosition.value = spawnPoint.value!.instance.position
}

const confirm = () => {
  const position = spawnPoint.value!.instance.position
  theme.value!.modelMeta!.spawnPointPosition = {
    x: position.x,
    y: position.y,
    z: position.z
  }
  reset()
  message.success('设置成功')
}

const cancel = () => {
  reset()
}

const reset = () => {
  isEdit.value = false
  const position = theme.value!.modelMeta?.spawnPointPosition || { x: 0, y: 4, z: 0 }
  spawnPoint.value?.instance.position.set(position.x, position.y, position.z)
  defaultPosition.value = new Vector3(position.x, position.y, position.z)
}

const init = () => {
  reset()
  useEmitt({ name: 'spawnPointEdit', callback: edit })
  useEmitt({ name: 'spawnPointConfirm', callback: confirm })
  useEmitt({ name: 'spawnPointCancel', callback: cancel })
}

// 不要使用 await
loader.loader(() => {
  init()
})
</script>

<template>
  <Cylinder
    ref="spawnPoint"
    :args="[0.5, 0.5, 2.8, 32, 1, false, 0, Math.PI * 2]"
    name="spawnPoint"
    color="orange"
    :position="defaultPosition"
    :visible="false"
  />

  <TransformControls
    v-if="isEdit && spawnPoint?.instance"
    :object="spawnPoint!.instance"
  />
</template>

<style scoped lang="scss"></style>
